package com.demo.config;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ObjectRedisTemplate extends RedisTemplate<String,Object> {
    public ObjectRedisTemplate(RedisConnectionFactory rcf) {
        setConnectionFactory(rcf);
        setKeySerializer(RedisSerializer.string());
        setValueSerializer(RedisSerializer.json());
        setHashKeySerializer(RedisSerializer.string());
        setHashValueSerializer(RedisSerializer.string());
        afterPropertiesSet();
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key,Class<T> type) {
        return (T)opsForValue().get(key);
    }

    public void addHashObject(String key,Object obj) {
        Class<?> type = obj.getClass();
        Field[] fields = type.getDeclaredFields();
        Map<String, Object> maps = new HashMap<>();
        for(Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(obj);
                maps.put(field.getName(), value.toString());
                field.setAccessible(false);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        opsForHash().putAll(key, maps);
    }
}
